import {AuthGuard} from "@nestjs/passport";
import {ExecutionContext, HttpStatus, Injectable, UnauthorizedException} from "@nestjs/common";
import {MyHttpException} from "../../common/exception/MyHttpException";
import {Reflector} from "@nestjs/core";
import {SKIP_AUTH_KEY} from "./GlobalGuardProvider";
import config from "../../config";

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
    constructor(private reflector: Reflector) {
        super();
    }

    canActivate(context: ExecutionContext) {
        // 在这里添加自定义的认证逻辑
        // 例如调用 super.logIn(request) 来建立一个session

        const isPublic = this.reflector.getAllAndOverride<boolean>(SKIP_AUTH_KEY, [
            context.getHandler(),
            context.getClass(),
        ]);
        if (config.localDebug) {
            console.log("本地调试，直接放行...");
            return true;
        }
        // 如果是带有放行注解的，直接放行
        if (isPublic) {
            return true;
        }

        // console.log('canActivate is invoked....');
        return super.canActivate(context);
    }

    handleRequest(err, user, info) {
        // 可以抛出一个基于info或者err参数的异常
        if (err || !user) {
            console.log('未登录，不允许放行...')
            throw err || new UnauthorizedException();
        }
        return user;
    }
}
